package net.dipper.tankwar.editor.ui;

import java.awt.Point;

import net.dipper.tankwar.core.data.ObjectMap;
import net.dipper.tankwar.core.helper.ViewPort;
import net.dipper.tankwar.core.config.ConfigItem;
import net.dipper.tankwar.core.config.ObjectItem;

public class EditorContext {
	public static int MODE_DISPLAY = 0;
	public static int MODE_EDIT = 1;
	public static int DEFAULT_V_WIDTH = 20;
	public static int DEFAULT_V_HEIGHT = 20;
	
	private ConfigItem currentItem;
	private int selectedX;
	private int selectedY;
	private int mode;
	private ObjectMap map;
	private ViewPort viewPort;
	private int cursorX;
	private int cursorY;
	private boolean isDirty;	//标记文件是否被修改过
	
	public EditorContext(ObjectMap objectMap){
		mode = MODE_DISPLAY;
		map = objectMap;
		viewPort = new ViewPort(0, 0, DEFAULT_V_WIDTH, DEFAULT_V_HEIGHT);
		cursorX = 0;
		cursorY = 0;
		isDirty = false;
	}

	public void setCurrentItem(ConfigItem item) {
		this.currentItem = item;
	}
	
	public void setMode(int mode){
		this.mode = mode;
	}
	
	public ConfigItem getCurrentItem(){
		return this.currentItem;
	}
	
	public int getMode(){
		return this.mode;
	}

	public ObjectMap getMap() {
		return this.map;
	}

	public void setViewPort(int x, int y, int width, int height) {
		this.viewPort = new ViewPort(x, y, width, height);
	}
	
	public ViewPort getViewPort(){
		return new ViewPort(this.viewPort.x, this.viewPort.y, this.viewPort.width, this.viewPort.height);
	}

	public void setCursor(int i, int j) {
		if(i < this.map.getWidth() && i >= 0)
			this.cursorX = i;
		if(j < this.map.getHeight() && j >= 0)
			this.cursorY = j;
	}

	public Point getCursor() {
		return new Point(this.cursorX, this.cursorY);
	}

	public void add() {
		if(this.currentItem != null){
			switch(currentItem.getLayer()){
			case 1:
				//背景层
				this.map.setBackground(cursorX + viewPort.x, cursorY + viewPort.y, currentItem.getValue());
				this.isDirty = true;
				break;
			
			case 2:
				//单位层
				ObjectItem item = (ObjectItem)currentItem;
				int x = cursorX + viewPort.x;
				int y = cursorY + viewPort.y;
				this.map.setObject(cursorX + viewPort.x, cursorY + viewPort.y, item.getValue());
				this.map.setHealth(x, y, item.getDefendence());
				this.isDirty = true;
				break;
			}
		}
	}

	public void select() {
		selectedX = cursorX;
		selectedY = cursorY;
	}
	
	public Point getSelected(){
		return new Point(selectedX, selectedY);
	}

	
	public void setIsDirty(boolean isDirty) {
		this.isDirty = isDirty;
	}

	public boolean getIsDirty() {
		return this.isDirty;
	}

	//设置地图，此方法会重置相关属性
	public void setMap(ObjectMap map) {
		this.map = map;
		this.currentItem = null;
		this.cursorX = 0;
		this.cursorY = 0;
		this.isDirty = false;
		this.mode = MODE_DISPLAY;
		this.selectedX = 0;
		this.selectedY = 0;
	}
}
